package com.LJH.WebTask3.controller;

import com.LJH.WebTask3.entity.Book;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Controller
@SessionAttributes("bookList")
public class BkListController {
    @GetMapping("/booklist")
    public String getBookList(Model model, @SessionAttribute(required = false) List<Book> bookList) {
        if (bookList == null) {
            bookList = new ArrayList<>();
        }
        model.addAttribute("bookList", bookList);
        return "BookList";
    }

    @GetMapping("/register")
    public String registerForm() {
        return "Registration";
    }

    @PostMapping("/register")
    public String register(@SessionAttribute List<Book> bookList,
                           @RequestParam String bookName,
                           @RequestParam String author,
                           @RequestParam String press,
                           @RequestParam String publicDate,
                           @RequestParam int surplus) {
        Book book = new Book(bookName, author, press, publicDate, surplus);
        bookList.add(book);
        return "Registration";
    }

    @GetMapping("/delete")
    public String delete(@SessionAttribute List<Book> bookList,
                         @RequestParam int index) {
        bookList.remove(index);
        return "BookList";
    }

    @GetMapping("/edit")
    public String editForm(Model model, @SessionAttribute List<Book> bookList,
                           @RequestParam int index) {
        Book book = bookList.get(index);
        model.addAttribute("bookList", book);
        model.addAttribute("index", index);
        return "Edit";
    }

    @PostMapping("/edit")
    public String edit(Model model, @SessionAttribute List<Book> bookList,
                       @RequestParam String bookName,
                       @RequestParam String author,
                       @RequestParam String press,
                       @RequestParam String publicDate,
                       @RequestParam int surplus,
                       @RequestParam int index) {
        Book book = bookList.get(index);
        book.setName(bookName);
        book.setAuthor(author);
        book.setPress(press);
        book.setPublicDate(publicDate);
        book.setSurplus(surplus);
        model.addAttribute("bookList", bookList);
        return "BookList";
    }
}
